package com.xiaoyu.lingdian.controller;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xiaoyu.lingdian.core.cache.RedisOper;
import com.xiaoyu.lingdian.core.mybatis.page.Page;
import com.xiaoyu.lingdian.entity.CoreAttachment;
import com.xiaoyu.lingdian.entity.CoreIntegral;
import com.xiaoyu.lingdian.entity.CoreUser;
import com.xiaoyu.lingdian.entity.weixin.Constant;
import com.xiaoyu.lingdian.service.CoreAttachmentService;
import com.xiaoyu.lingdian.service.CoreIntegralService;
import com.xiaoyu.lingdian.service.CoreUserService;
import com.xiaoyu.lingdian.tool.RandomUtil;
import com.xiaoyu.lingdian.tool.Validators;
import com.xiaoyu.lingdian.tool.encrypt.MD5Util;
import com.xiaoyu.lingdian.tool.init.ConfigIni;
import com.xiaoyu.lingdian.tool.out.ResultMessageBuilder;
import com.xiaoyu.lingdian.tool.wx.OAuthUtil;
import com.xiaoyu.lingdian.vo.CoreUserVO;

@Controller
@RequestMapping(value="/coreUser")
public class CoreUserController extends BaseController {

	/**
	 * 用户表
	 */
	@Autowired
	private CoreUserService coreUserService;

	/**
	 * 附件表
	 */
	@Autowired
	private CoreAttachmentService coreAttachmentService;
	
	/**
	 * 积分攻略表
	 */
	@Autowired
	private CoreIntegralService coreIntegralService;
	
	/**
	 * redis工具
	 */
	@Autowired
	private RedisOper redisOper;
	
	/**
	 * 根据用户名称、手机号码分页查询用户列表
	 * 
	 * @param crusrName
	 * @param crusrMobile
	 * @param pageNum
	 * @param pageSize
	 * @param response
	 */
	@RequestMapping(value = "/find/by/cnd", method = RequestMethod.POST)
	public void findByCnd(String crusrName, String crusrMobile, Integer pageNum, Integer pageSize, HttpServletResponse response) {
		logger.info("[CoreUserController.findByCnd]:begin findByCnd.");
		if (pageNum == null) {
			pageNum = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		Page<CoreUser> page = coreUserService.findCoreUserByCnd(crusrName, crusrMobile, pageNum, pageSize);
		Page<CoreUserVO> pageVO = new Page<>(page.getPageNumber(), page.getPageSize(), page.getTotalCount());		
		List<CoreUserVO> volist = new ArrayList<>();
		CoreUserVO vo = new CoreUserVO();
		for (CoreUser coreUser : page.getResult()) {
			vo = new CoreUserVO();
			vo.convertPOToVO(coreUser);
			//查询头像附件UUID
			List<CoreAttachment> list = coreAttachmentService.findCoreAttachmentByCnd(coreUser.getCrusrUuid());
			if (list != null && list.size() > 0) {
				vo.setHeadUuid(list.get(0).getCratmUuid());
			}
			volist.add(vo);
		}
		pageVO.setResult(volist);
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "查询人员列表成功", pageVO), response);
		logger.info("[CoreUserController.findByCnd]:end findByCnd.");
	}
	
	/**
	 * 查看个人信息详情
	 * 
	 * @param crusrUuid
	 * @param response
	 */
	@RequestMapping(value="/views", method=RequestMethod.POST)
	public void viewsUser(String crusrUuid, HttpServletResponse response) {
		logger.info("[CoreUserController.viewsUser]:begin viewsUser");
		if (StringUtils.isBlank(crusrUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "缺少crusrUuid参数！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(crusrUuid);
		coreUser = coreUserService.getCoreUser(coreUser);
		CoreUserVO vo = new CoreUserVO();
		vo.convertPOToVO(coreUser);
		//查询头像附件UUID
		List<CoreAttachment> list = coreAttachmentService.findCoreAttachmentByCnd(crusrUuid);
		if (list != null && list.size() > 0) {
			vo.setHeadUuid(list.get(0).getCratmUuid());
		}		
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "查询个人信息详情成功！", vo), response);
		logger.info("[CoreUserController.viewsUser]:end viewsUser");
	}
	
	/**
	 * 查看个人积分和抵扣比例
	 * 
	 * @param crusrUuid
	 * @param response
	 */
	@RequestMapping(value="/views/score", method=RequestMethod.POST)
	public void viewsScore(String crusrUuid, HttpServletResponse response) {
		logger.info("[CoreUserController.viewsScore]:begin viewsScore");
		if (StringUtils.isBlank(crusrUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "缺少crusrUuid参数！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(crusrUuid);
		coreUser = coreUserService.getCoreUser(coreUser);
		CoreUserVO vo = new CoreUserVO();
		vo.convertPOToVO(coreUser);
		Integer points = 0;
		CoreIntegral coreIntegral = new CoreIntegral();
		coreIntegral.setCriglUuid("CCCCC");
		coreIntegral = coreIntegralService.getCoreIntegral(coreIntegral);
		if (coreIntegral != null) {
			String criglScore = coreIntegral.getCriglScore();
			points = Integer.valueOf(criglScore.substring(0, criglScore.length()-1));    //3）每累计20积分可抵扣1元费用
		}	
		Double bl = points / 20.0;
		vo.setJfdkbl(bl.toString());
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "查看个人积分和抵扣比例成功！", vo), response);
		logger.info("[CoreUserController.viewsScore]:end viewsScore");
	}
	
	/**
	 * 后台重置密码
	 * 
	 * @param crusrUuid
	 * @param password
	 * @param response
	 */
	@RequestMapping(value = "/reset/pwd", method = RequestMethod.POST)
	public void resetPwd(String crusrUuid, String password, HttpServletResponse response) {
		logger.info("[CoreUserController.resetPwd]:begin resetPwd.");
		if (StringUtils.isBlank(crusrUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入uuid！"), response);
			return;
		}		
		if (StringUtils.isBlank(password)) {
			password = "123456";
		}
		String md5PWD = MD5Util.getMD5(password);
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(crusrUuid);
		coreUser.setCrusrPassword(md5PWD);
		coreUser.setCrusrUdate(new Date());
		coreUserService.updateCoreUser(coreUser);
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "重置密码成功！"), response);
		logger.info("[CoreUserController.resetPwd]:end resetPwd.");
	}
	
	/**
	 * 忘记密码发送短信
	 * 
	 * @param crusrMobile
	 * @param response
	 */
	@RequestMapping(value="/forget/send", method=RequestMethod.POST)
	public void forgetSendSms(String crusrMobile, HttpServletResponse response) {
		logger.info("[CoreUserController.forgetSendSms]:begin forgetSendSms");	
		if (StringUtils.isBlank(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入手机号！"), response);
			return;
		}
		if(!Validators.isMobile(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "手机号格式非法！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrMobile(crusrMobile);	
		if(coreUserService.getCoreUserByMobile(coreUser) == null) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "该手机号不存在，请先注册！"), response);
			return;
		}
		/**
		//正式开始---------------
		String nowday = DateUtil.getTodayTextYMD();
		String strCount = redisOper.get("jgj.count."+nowday+"."+crusrMobile);
		if (null != strCount && !("").equals(strCount)) {
			try {
				int count = Integer.valueOf(strCount);
				if (count >= 10) {
					writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "你今日发送验证码已超过10条！"), response);
					return;
				}
			} catch (Exception e) {
				writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "解析失败,发送忘记密码验证码失败！"), response);
				return;
			}
		}
		String message = RandomUtil.generateMixNum(4);	
		boolean flag = SendSMSUtil.sendForget(crusrMobile, message);		
		if (flag) {
			//存入redis中
			redisOper.set("jgj.code."+crusrMobile, message, 600);
			redisOper.incr("jgj.count."+nowday+"."+crusrMobile);
			writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "发送忘记密码验证码成功！"), response);
		} else {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "发送忘记密码验证码失败！"), response);
		}
		//正式结束------------------
		 */
		//测试开始------------------
		redisOper.set("jgj.code."+crusrMobile, "8888", 600);
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "发送忘记密码验证码成功,默认为8888！"), response);
		//测试结束------------------
		logger.info("[CoreUserController.forgetSendSms]:end forgetSendSms");
	}
	
	/**
	 * 忘记密码
	 * 
	 * @param crusrMobile
	 * @param code 验证码
	 * @param crusrPassword
	 * @param response
	 */
	@RequestMapping(value="/forget", method=RequestMethod.POST)
	public void forget(String crusrMobile, String code, String crusrPassword, HttpServletResponse response) {
		logger.info("[CoreUserController.forget]:begin forget");
		if (StringUtils.isBlank(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入手机号！"), response);
			return;
		}
		if(!Validators.isMobile(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "手机号格式非法！"), response);
			return;
		}
		String strCode = redisOper.get("jgj.code."+crusrMobile);
		if (null == strCode || ("").equals(strCode)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "验证码已过期，请重新发送短信验证码！"), response);
			return;
		}
		if (!strCode.equals(code)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "短信验证码验证失败！"), response);
			return;
		}
		if (StringUtils.isBlank(crusrPassword)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入密码！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrMobile(crusrMobile);	
		if(coreUserService.getCoreUserByMobile(coreUser) == null) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "该手机号不存在，请先注册！"), response);
			return;
		}
		String md5PWD = MD5Util.getMD5(crusrPassword);
		coreUser.setCrusrPassword(md5PWD);
		coreUserService.updateCoreUserByMobile(coreUser);		
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "修改忘记密码成功！"), response);
		logger.info("[CoreUserController.forget]:end forget");
	}
	
	/**
	 * 积分兑换余额
	 * @param crusrUuid
	 * @param oldPwd
	 * @param response
	 */
	@RequestMapping(value = "/update/rechargePoint", method = RequestMethod.POST)
	public void rechargePoint(String crusrUuid, int exchangePoint, HttpServletResponse response) {
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(crusrUuid);
		CoreUser coreUserN = coreUserService.getCoreUser(coreUser);
		
		double exchangeRate = 50D/1000D;
		double exchangeMoney = exchangePoint*exchangeRate;
		DecimalFormat df = new DecimalFormat("0.00");//格式化小数   
		String exchangeMoneyS = df.format(exchangeMoney);//返回的是String类型 
		
		logger.info(exchangeRate+"[CoreUserController.rechargePoint]要兑换的积分数："+exchangePoint+"可兑换余额："+exchangeMoney);
		
		//增加用户余额
		coreUserN.setCrusrBalance(Double.valueOf(exchangeMoneyS));
		coreUserService.updateCoreUserBalanceAdd(coreUserN);
		
		//减去用户积分
		coreUserN.setCrusrPoints(exchangePoint);
		coreUserService.updateCoreUserPointsDesc(coreUserN);
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "积分兑换余额成功！"), response);
		logger.info("[CoreUserController.rechargePoint]:end rechargePoint.");
	}
	
	/**
	 * 修改密码
	 * 
	 * @param crusrName
	 * @param oldPwd
	 * @param newPwd
	 * @param confirmPwd
	 * @param response
	 */
	@RequestMapping(value = "/update/pwd", method = RequestMethod.POST)
	public void updatePwd(String crusrUuid, String oldPwd, String newPwd, String confirmPwd, HttpServletResponse response) {
		logger.info("[CoreUserController.updatePwd]:begin updatePwd.");
		//if (isSession(request)) {
    	//	writeAjaxJSONResponse(ResultMessageBuilder.build(false, SESSION_TIMEOUTCODE, "您的操作已过时，请重新登录"), response);
		//	return;
		//}
		if (StringUtils.isBlank(crusrUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入uuid！"), response);
			return;
		}		
		if (StringUtils.isBlank(oldPwd)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入旧密码！"), response);
			return;
		}		
		if (StringUtils.isBlank(newPwd)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入新密码！"), response);
			return;
		}		
		if (StringUtils.isBlank(confirmPwd)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入确认密码！"), response);
			return;
		}		
		if (!newPwd.equals(confirmPwd)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "密码输入不一致！"), response);
			return;
		}		
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(crusrUuid);
		coreUser = coreUserService.getCoreUser(coreUser);
		String md5PWDOld = MD5Util.getMD5(oldPwd);
		if(coreUser == null || !md5PWDOld.equals(coreUser.getCrusrPassword())) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "密码错误！"), response);
			return;
		}
		String md5PWDNew = MD5Util.getMD5(newPwd);
		coreUser.setCrusrPassword(md5PWDNew);
		coreUser.setCrusrUdate(new Date());
		coreUserService.updateCoreUser(coreUser);
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "修改密码成功！"), response);
		logger.info("[CoreUserController.updatePwd]:end updatePwd.");
	}
	
	/**
	 * 注册发送短信
	 * 
	 * @param crusrMobile
	 * @param response
	 */
	@RequestMapping(value="/register/send", method=RequestMethod.POST)
	public void registerSendSms(String crusrMobile, HttpServletResponse response) {
		logger.info("[CoreUserController.registerSendSms]:begin registerSendSms");	
		if (StringUtils.isBlank(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入手机号！"), response);
			return;
		}
		if(!Validators.isMobile(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "手机号格式非法！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrMobile(crusrMobile);	
		if(coreUserService.getCoreUserByMobile(coreUser) != null) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "该手机号已存在，请重新输入！"), response);
			return;
		}
		/**
		//正式开始---------------
		String nowday = DateUtil.getTodayTextYMD();
		String strCount = redisOper.get("jgj.count."+nowday+"."+crusrMobile);
		if (null != strCount && !("").equals(strCount)) {
			try {
				int count = Integer.valueOf(strCount);
				if (count >= 10) {
					writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "你今日发送验证码已超过10条！"), response);
					return;
				}
			} catch (Exception e) {
				writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "解析失败,发送注册验证码失败！"), response);
				return;
			}
		}
		String message = RandomUtil.generateMixNum(4);	
		boolean flag = SendSMSUtil.sendRegister(crusrMobile, message);		
		if (flag) {
			//存入redis中
			redisOper.set("jgj.code."+crusrMobile, message, 600);
			redisOper.incr("jgj.count."+nowday+"."+crusrMobile);
			writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "发送注册验证码成功！"), response);
		} else {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "发送注册验证码失败！"), response);
		}
		//正式结束------------------
		 */
		//测试开始------------------
		redisOper.set("jgj.code."+crusrMobile, "8888", 600);
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "发送注册验证码8888成功！"), response);
		//测试结束------------------
		
		logger.info("[CoreUserController.registerSendSms]:end registerSendSms");
	}
	
	/**
	 * 注册
	 * 
	 * @param crusrMobile
	 * @param crusrPassword
	 * @param code 验证码
	 * @param openCode 授权code值
	 * @param crusrType
	 * @param crusrPoints
	 * @param response
	 */
	@RequestMapping(value="/register", method=RequestMethod.POST)
	public void register(String crusrMobile, String crusrPassword, String code, String openCode, Integer crusrType, Integer crusrPoints, HttpServletResponse response) {
		logger.info("[CoreUserController.register]:begin register");
		if (StringUtils.isBlank(code)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入验证码！"), response);
			return;
		}
		if (StringUtils.isBlank(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入手机号！"), response);
			return;
		}
		if(!Validators.isMobile(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "手机号格式非法！"), response);
			return;
		}
		String strCode = redisOper.get("jgj.code."+crusrMobile);
		if (null == strCode || ("").equals(strCode)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "验证码已过期，请重新发送短信验证码！"), response);
			return;
		}
		if (!strCode.equals(code)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "短信验证码验证失败！"), response);
			return;
		}
		if (StringUtils.isBlank(crusrPassword)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入密码！"), response);
			return;
		}
		if (crusrType == null) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入等级！"), response);
			return;
		}
		if (crusrPoints == null) {
			crusrPoints = 0;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrMobile(crusrMobile);	
		if(coreUserService.getCoreUserByMobile(coreUser) != null) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "该手机号已存在，请重新输入！"), response);
			return;
		}
		coreUser.setCrusrName(crusrMobile);
		coreUser.setCrusrStatus(1);
		coreUser.setCrusrType(crusrType);
		coreUser.setCrusrCdate(new Date());
		String uuid = RandomUtil.generateString(16);
		coreUser.setCrusrUuid(uuid);
		String md5PWD = MD5Util.getMD5(crusrPassword);
		coreUser.setCrusrPassword(md5PWD);
		if (crusrPoints == 0) { //1）新注册用户获得100积分
			CoreIntegral coreIntegral = new CoreIntegral();
			coreIntegral.setCriglUuid("AAAAA");
			coreIntegral = coreIntegralService.getCoreIntegral(coreIntegral);
			if (coreIntegral != null) {
				String criglScore = coreIntegral.getCriglScore();
				crusrPoints = Integer.valueOf(criglScore.substring(0, criglScore.length()-1));    //新注册用户获得100积分
			}
		}
		coreUser.setCrusrPoints(crusrPoints);
		Double balance = 0.0;
		coreUser.setCrusrBalance(balance);
		if (!StringUtils.isBlank(openCode)) {
			String strToken = OAuthUtil.getToken(ConfigIni.getIniStrValue("WEIXIN_CONFIG", "appid", Constant.APP_ID), ConfigIni.getIniStrValue("WEIXIN_CONFIG", "appsecret", Constant.APP_SECRET), "authorization_code", openCode);
			logger.info("授权access_token:" +  strToken); //跟平常调用的access_token不一样,没请求次数限制,不做缓存
			/**
			{
				"access_token":"ACCESS_TOKEN",
				"expires_in":7200,
				"refresh_token":"REFRESH_TOKEN",
				"openid":"OPENID",
				"scope":"SCOPE",
				"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
			}
			**/
			try {
				JSONObject jsonObject = JSONObject.fromObject(strToken);
				if (jsonObject != null && jsonObject.get("openid") != null) {
					coreUser.setCrusrOpenid(jsonObject.get("openid").toString());
				}
			} catch (Exception e) {
			}		
		}
		coreUserService.insertCoreUser(coreUser);		
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "注册成功！",uuid), response);
		logger.info("[CoreUserController.register]:end register");
	}
	
	/**
	 * 后台添加用户
	 * 
	 * @param crusrName
	 * @param crusrCode
	 * @param crusrPassword
	 * @param crusrIdNumber
	 * @param crusrEmail
	 * @param crusrMobile
	 * @param crusrType
	 * @param crusrBirthday
	 * @param crusrGender
	 * @param crusrQq
	 * @param crusrAddress
	 * @param crusrBalance
	 * @param crusrPoints
	 * @param crusrRemarks
	 * @param crusrOpenid
	 * @param uuids
	 * @param response
	 */
	@RequestMapping(value="/add/user", method=RequestMethod.POST)
	public void addUesr(String crusrName, String crusrCode, String crusrPassword, String crusrIdNumber, String crusrEmail, String crusrMobile,
			Integer crusrType, String crusrBirthday, Integer crusrGender, String crusrQq, String crusrAddress, String crusrBalance,
			Integer crusrPoints, String crusrRemarks, String crusrOpenid, String uuids, HttpServletResponse response) {
		logger.info("[CoreUserController.addUesr]:begin addUesr");
		if (StringUtils.isBlank(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入手机号！"), response);
			return;
		}
		if(!Validators.isMobile(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "手机号格式非法！"), response);
			return;
		}
		if (StringUtils.isBlank(crusrName)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入昵称！"), response);
			return;
		}
		if (StringUtils.isBlank(crusrPassword)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入密码！"), response);
			return;
		}
		if (crusrType == null) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入等级！"), response);
			return;
		}
		if (crusrPoints == null) {
			crusrPoints = 0;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrMobile(crusrMobile);	
		if(coreUserService.getCoreUserByMobile(coreUser) != null) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "该手机号已存在，请重新输入！"), response);
			return;
		}
		coreUser.setCrusrName(crusrName);
		coreUser.setCrusrAddress(crusrAddress);
		coreUser.setCrusrBirthday(crusrBirthday);
		coreUser.setCrusrCode(crusrCode);
		coreUser.setCrusrEmail(crusrEmail);
		coreUser.setCrusrGender(crusrGender);
		coreUser.setCrusrIdNumber(crusrIdNumber);
		coreUser.setCrusrQq(crusrQq);
		coreUser.setCrusrRemarks(crusrRemarks);
		coreUser.setCrusrStatus(1);
		coreUser.setCrusrType(crusrType);
		coreUser.setCrusrCdate(new Date());
		String uuid = RandomUtil.generateString(16);
		coreUser.setCrusrUuid(uuid);
		String md5PWD = MD5Util.getMD5(crusrPassword);
		coreUser.setCrusrPassword(md5PWD);
		coreUser.setCrusrOpenid(crusrOpenid);
		if (crusrPoints == 0) { //注册获得积分
			CoreIntegral coreIntegral = new CoreIntegral();
			coreIntegral.setCriglUuid("AAAAA");
			coreIntegral = coreIntegralService.getCoreIntegral(coreIntegral);
			if (coreIntegral != null) {
				String criglScore = coreIntegral.getCriglScore();
				crusrPoints = Integer.valueOf(criglScore.substring(0, criglScore.length()-1));    //新注册用户获得100积分
			}
		}
		coreUser.setCrusrPoints(crusrPoints);
		Double balance = 0.0;		
		if (!StringUtils.isBlank(crusrBalance)) {			
			try {
				balance = Double.parseDouble(crusrBalance);
			} catch (Exception e) {
				writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入正确的余额！"), response);
				return;
			}
		}
		coreUser.setCrusrBalance(balance);
		coreUserService.insertCoreUser(coreUser);
		//添加头像
		if (!StringUtils.isBlank(uuids)) {
			CoreAttachment coreAttachment = new CoreAttachment();
			String[] uuidModel = uuids.split("\\|");
			for (int i = 0; i < uuidModel.length; i++) {
				coreAttachment = new CoreAttachment();
				coreAttachment.setCratmUuid(uuidModel[i]);
				coreAttachment.setCratmBusUuid(uuid);
				coreAttachmentService.updateCoreAttachment(coreAttachment);
			}
		}		
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "添加个人信息成功！",uuid), response);
		logger.info("[CoreUserController.addUesr]:end addUesr");
	}
	
	/**
	 * 修改用户
	 * 
	 * @param crusrUuid
	 * @param crusrName
	 * @param crusrCode
	 * @param crusrIdNumber
	 * @param crusrEmail
	 * @param crusrMobile
	 * @param crusrType
	 * @param crusrBirthday
	 * @param crusrGender
	 * @param crusrQq
	 * @param crusrAddress
	 * @param crusrRemarks
	 * @param crusrOpenid
	 * @param uuids
	 * @param response
	 */
	@RequestMapping(value="/update/user", method=RequestMethod.POST)
	public void updateUesr(String crusrUuid, String crusrName, String crusrCode, String crusrIdNumber, String crusrEmail, String crusrMobile,
			Integer crusrType, String crusrBirthday, Integer crusrGender, String crusrQq, String crusrAddress, 
			String uuids, String crusrRemarks, String crusrOpenid, HttpServletResponse response) {
		logger.info("[CoreUserController.updateUesr]:begin updateUesr");	
		if (StringUtils.isBlank(crusrUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入crusrUuid！"), response);
			return;
		}
		if (StringUtils.isBlank(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入手机号！"), response);
			return;
		}
		if(!Validators.isMobile(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "手机号格式非法！"), response);
			return;
		}
		if (StringUtils.isBlank(crusrName)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入昵称！"), response);
			return;
		}
		if (crusrType == null) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入等级！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(crusrUuid);
		coreUser.setCrusrName(crusrName);
		coreUser.setCrusrAddress(crusrAddress);
		coreUser.setCrusrBirthday(crusrBirthday);
		coreUser.setCrusrCode(crusrCode);
		coreUser.setCrusrEmail(crusrEmail);
		coreUser.setCrusrGender(crusrGender);
		coreUser.setCrusrIdNumber(crusrIdNumber);
		coreUser.setCrusrMobile(crusrMobile);
		coreUser.setCrusrQq(crusrQq);
		coreUser.setCrusrRemarks(crusrRemarks);
		coreUser.setCrusrType(crusrType);
		coreUser.setCrusrUdate(new Date());
		coreUser.setCrusrOpenid(crusrOpenid);
		coreUserService.updateCoreUser(coreUser);
		if (!StringUtils.isBlank(uuids)) {
			CoreAttachment coreAttachment = new CoreAttachment();
			String[] uuidModel = uuids.split("\\|");
			for (int i = 0; i < uuidModel.length; i++) {
				coreAttachment = new CoreAttachment();
				coreAttachment.setCratmUuid(uuidModel[i]);
				coreAttachment.setCratmBusUuid(crusrUuid);
				coreAttachmentService.updateCoreAttachment(coreAttachment);
			}
		}
				
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "修改个人信息成功！"), response);
		logger.info("[CoreUserController.updateUesr]:end updateUesr");
	}
	
	/**
	 * 修改用户
	 * 
	 * @param crusrUuid
	 * @param crusrBalance
	 * @param response
	 */
	@RequestMapping(value="/update/crusrBalance", method=RequestMethod.POST)
	public void updateUrusrBalance(String crusrUuid, String crusrBalance, HttpServletResponse response) {
		logger.info("[CoreUserController.updateUrusrBalance]:begin updateUrusrBalance");	
		if (StringUtils.isBlank(crusrUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入crusrUuid！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(crusrUuid);
		coreUser.setCrusrBalance(Double.valueOf(crusrBalance));
		coreUser.setCrusrUdate(new Date());
		coreUserService.updateCoreUser(coreUser);
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "修改个人余额！"), response);
		logger.info("[CoreUserController.updateUrusrBalance]:end updateUrusrBalance");
	}
	
	/**
	 * 判断手机号是否已存在
	 * 
	 * @param crusrMobile
	 * @param response
	 */
	@RequestMapping(value="/valid/mobile", method=RequestMethod.POST)
	public void validMobile(String crusrMobile, HttpServletResponse response) {
		logger.info("[CoreUserController.validMobile]:begin validMobile");	
		if (StringUtils.isBlank(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入手机号！"), response);
			return;
		}
		if(!Validators.isMobile(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "手机号格式非法！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrMobile(crusrMobile);
		if(coreUserService.getCoreUserByMobile(coreUser) != null) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "该手机号已存在！"), response);
			return;
		}
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "该手机号可用！"), response);
		logger.info("[CoreUserController.validMobile]:end validMobile");
	}
	
	/**
	 * 判断用户名称是否已存在
	 * 
	 * @param crusrName
	 * @param response
	 */
	@RequestMapping(value="/valid/name", method=RequestMethod.POST)
	public void validName(String crusrName, HttpServletResponse response) {
		logger.info("[CoreUserController.validName]:begin validName");	
		if (StringUtils.isBlank(crusrName)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入昵称！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrName(crusrName);
		if(coreUserService.getCoreUserByName(coreUser) != null) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "该昵称已存在！"), response);
			return;
		}
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "该昵称可用！"), response);
		logger.info("[CoreUserController.validName]:end validName");
	}
	
	/**
	 * 登录
	 * 
	 * @param crusrMobile
	 * @param crusrPassword
	 * @param code 授权code值
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public void login(String crusrMobile, String crusrPassword, String code, HttpServletRequest request, HttpServletResponse response) {
		logger.info("[CoreUserController.login]:begin login.");
		if (StringUtils.isBlank(crusrMobile)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入手机号！"), response);
			return;
		}		
		if (StringUtils.isBlank(crusrPassword)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入密码！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrMobile(crusrMobile);
		coreUser = coreUserService.getCoreUserByMobile(coreUser);
		String md5PWD = MD5Util.getMD5(crusrPassword);
		if(coreUser == null || !md5PWD.equals(coreUser.getCrusrPassword())) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "密码错误！"), response);
			return;
		}
		//super.removeSession(request);
		//super.setSession(request, cractName);
		CoreUserVO vo = new CoreUserVO();
		vo.convertPOToVO(coreUser);
		//查询头像附件UUID
		List<CoreAttachment> list = coreAttachmentService.findCoreAttachmentByCnd(coreUser.getCrusrUuid());
		if (list != null && list.size() > 0) {
			vo.setHeadUuid(list.get(0).getCratmUuid());
		}
		if (vo.getCrusrOpenid() == null || ("").equals(vo.getCrusrOpenid())) {
			if (!StringUtils.isBlank(code)) {
				String strToken = OAuthUtil.getToken(ConfigIni.getIniStrValue("WEIXIN_CONFIG", "appid", Constant.APP_ID), ConfigIni.getIniStrValue("WEIXIN_CONFIG", "appsecret", Constant.APP_SECRET), "authorization_code", code);
				logger.info("授权access_token:" +  strToken); //跟平常调用的access_token不一样,没请求次数限制,不做缓存
				/**
				{
					"access_token":"ACCESS_TOKEN",
					"expires_in":7200,
					"refresh_token":"REFRESH_TOKEN",
					"openid":"OPENID",
					"scope":"SCOPE",
					"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
				}
				**/
				try {
					JSONObject jsonObject = JSONObject.fromObject(strToken);
					if (jsonObject != null && jsonObject.get("openid") != null) {
						coreUser.setCrusrOpenid(jsonObject.get("openid").toString());
						coreUserService.updateCoreUser(coreUser);
						vo.setCrusrOpenid(jsonObject.get("openid").toString());
					}
				} catch (Exception e) {
				}				
			}
		}
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "登录成功", vo), response);
		logger.info("[CoreUserController.login]:end login.");
	}
	
	/**
	 * 删除用户（彻底删除）
	 * 
	 * @param crusrUuid
	 * @param response
	 */
	@RequestMapping(value="/delete/one", method=RequestMethod.POST)
	public void deleteOne(String crusrUuid, HttpServletResponse response) {
		logger.info("[CoreUserController.deleteOne]:begin deleteOne");
		if (StringUtils.isBlank(crusrUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "缺少crusrUuid参数！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(crusrUuid);
		coreUserService.deleteCoreUser(coreUser);
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "删除用户成功！"), response);
		logger.info("[CoreUserController.deleteOne]:end deleteOne");
	}
	
	/**
	 * 批量删除用户
	 * 
	 * @param crusrUuids
	 * @param response
	 */
	@RequestMapping(value="/delete/batch", method=RequestMethod.POST)
	public void deleteBatch(String crusrUuids, HttpServletResponse response) {
		logger.info("[CoreUserController.deleteBatch]:begin deleteBatch");
		if (StringUtils.isBlank(crusrUuids)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请选择批量删除对象！"), response);
			return;
		}
		String[] array = crusrUuids.split("\\|");
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < array.length; i++) {
			list.add(array[i]);
		}
		if (list.size() == 0) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请选择批量删除对象！"), response);
			return;
		}
		coreUserService.deleteCoreUserByCnd(list);
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "删除用户成功！"), response);
		logger.info("[CoreUserController.deleteBatch]:end deleteBatch");
	}
	
}